package com.rahms.server.handler;

import com.rahms.common.constant.MessageConstant;
import com.rahms.common.handler.ApiException;
import com.rahms.common.result.R;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ApiException.class)
    public R<Object> handleApiException(ApiException e) {
        return R.error(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<Object> handleValidationException(MethodArgumentNotValidException e) {
        String msg = e.getBindingResult().getFieldError() != null ? e.getBindingResult().getFieldError().getDefaultMessage() : MessageConstant.PARAM_IS_INVALID;
        return R.error(msg);
    }

    @ExceptionHandler(Exception.class)
    public R<Object> handleGeneralException(Exception e) {
        return R.error(MessageConstant.SYSTEM_ERROR + ": " + e.getMessage());
    }
}


